#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "../include/content_search.h"
#include "../include/vfs.h"
	
int contentsearch(char word[] ,char filepath[])
{ 	
	np temp;
	int i,j=0;
	char input[1024],*send,*words;
	long saveblock;
	Block *b;
	trie_structure trie;
	content *content_root=NULL;
	FILE* fp,*out;

	//printf("\n WORD:%s",word);

	out = fopen(filepath,"w");

	if(out==NULL)
		return 1;

	header=(Header*)malloc(sizeof(Header));

	b=(Block*) malloc(sizeof(Block));
		
	fp=fopen(filesystem_name, "r+b");
	
	fread(header,sizeof(Header),1,fp);

	for(i=0;i<27;i++)
	{
		 	
		temp=roots.hashtable[i];
		
		if(temp!=NULL)
		{	
			temp=temp->next;

			while(temp!=NULL)
			{
			
				
					
				saveblock = temp->fdes->block_no;

					
					for(i=0;i<header->num_blocks;i++)
					{
						fread(b,sizeof(Block),1,fp);
		
						if (b->num==saveblock)					
						{
							initialize(&trie);
							
							strcpy(input,b->buffer);

							words = strtok(input," ");

							while(words)
						    	{	
								send = malloc(sizeof(char)*strlen(words));
						 		strcpy(send,words);

								words=strtok(NULL," ");

		
    						  // 	printf("\n INSERTING :%s \n",send);
        							insert_trie(&trie, send);
							}
							
						}

					}

				if(trie_search(&trie,word))
				{
					content_root = add_list(content_root,temp->fdes);
				}

				rewind(fp);
				fread(header,sizeof(Header),1,fp);

				
				
			temp=temp->next;
			}
		}
	}


	display_list(content_root,out);

	fclose(fp);

	return 0;

}


content * add_list(content *content_root,FD *fd)
{

	content *add;

	add = malloc(sizeof(content));
	add->link=NULL;

	strcpy(add->file,fd->filename);
	strcpy(add->full_path,fd->path);

	add->link = content_root;
	
	content_root = add;


	return content_root;

}


void display_list(content *root,FILE *out)
{
	content *head = root;

	if(head==NULL)	
	{
		fprintf(out,"\n NO FILES \n");
		fseek(out,0,SEEK_END);
		return;
	}

	while(head!=NULL)
	{

		fprintf(out,"THE FILES ARE: \n");

		fprintf(out,"%s \t %s \n",head->file,head->full_path);
		fseek(out,0,SEEK_END);

		head = head->link;
	}


}


	








